<template>
	<el-container v-loading="loading">
		<el-header>
			<div class="left-panel">
				<fsButton ref="button" plain size="default" :buttons="buttons" @clickHandler="buttonHandler"></fsButton>
			</div>
			<div class="right-panel">
				<ex-search ref="search" :searches="searches" @searchOk="searchHandler"></ex-search>
			</div>
		</el-header>
		<el-main class="nopadding" style="padding: 0 5px;">
			<el-table ref="table" :data="tableDatas"
					  row-key="id"
					  :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
					  lazy
					  :border=true
					  :stripe=true
					  :show-summary="true"
					  :load="loadChild">
				<template v-for="column in this.columns" :key="column.code">
					<el-table-column :prop="column.code"
									 :label="column.name"
									 :sortable="column.sortable?column.sortable:false"
									 :formatter="this.formatters"
									 :column-key="column.code"
									 :summary = "column.summary? column.summary:false"
									 :show-overflow-tooltip="true"
									 :width="column.width?column.width:null">

					</el-table-column>
				</template>
			</el-table>
		</el-main>
	</el-container>
	<data-card ref="dataCard"></data-card>
</template>

<script>
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import ExTreeNavigation from "@/components/exSearchTree/index.vue";
import ExSearchTree from "@/components/exSearchTree/index.vue";
import scSelectFilter from "@/components/scSelectFilter/index.vue";
import tool from "@/utils/tool";
import DataCard from "@/views/asset/card/card.vue";
import ExSelect from "@/components/exSelect/index.vue";
import globalparam from "@/constant/model/globalparam";
import {h} from "vue";
import {ElButton, ElContainer} from "element-plus";
export default {
	name: '位置汇总统计',
	components: {
		ExSelect,
		DataCard,
		scSelectFilter,
		ExSearchTree,
		ExTreeNavigation,
		ExSearch,
		ExTable,
	},
	data() {
		return {
			dialog: {
				save: false,
				permission: false,
			},
			apiObj: [],
			buttons: [
				{name: "导出", icon: "el-icon-download", click: "export",  type: "info", permission: "export"},
			],
			searches: [
				{type: "input", name: "位置名称", code: "positionName", placeholder: "请输入位置名称",},
				{type: "select", name: "资产状态", code: "assetStatusIds", placeholder: "请选择资产状态", dictCode:'ASSET_STATUS',multiple:true},
				{type: "tree-select", name: "使用部门", code: "deptIds", placeholder: "请选择使用部门", dictCode:'SysOrganization',checkStrictly:true,multiple:true,dataPermissionProcess:true,permissionData:this.$TOOL.current.readDeptIds()},
				{type: "daterange", name: "购置日期", code: "boughtDateStart,boughtDateEnd", placeholder: "请选择购置日期", formatter:"YYYY-MM-dd",valueFormat:"YYYYMMDD",range:30},
				{type: "select", name: "类型", code: "financialType", placeholder: "请选择类型", dictCode:'FINANCIAL_TYPE'},
			],
			columns: [
				{code: "name", name: "资产位置", width:""},
				{code: "assetCount", name: "资产数量",click:"show1", width:"150",summary: true},
				{code: "originalValue", name: "资产原值", width:"200",summary: true},
				{code: "netValue", name: "资产净值", width:"200",summary: true},
			],
			pathCode: '',
			pathCodes: [],
			pathCodeMap:{},
			tableDatas: [],
			excludeStatus:['delete'],
			loading: false,
			readDeptIds: this.$TOOL.current.readDeptIds(),
			// manageDeptIds: this.$TOOL.current.manageDeptIds(),
			manageAssetCategoryIds: this.$TOOL.current.manageAssetCategoryIds(),
			assetStatisticsRange: "",
		}
	},
	created() {
	},
	mounted() {
		this.$cache.data.loadGlobalParam(globalparam.assetStatisticsRange.paramCode).then((res) => {
			this.assetStatisticsRange = res;
			this.loadData();
		});
	},
	beforeMount() {
	},
	methods: {
		buttonHandler(index, name) {
			this.$options.methods[name](this, index);
		},

		searchHandler() {
			this.loadData();
		},
		columnClickHandler(name,data){
			this.$options.methods[name](this, data);
		},
		loadData(){
			let queryParams = {};
			this.loading = true;
			//释放搜索组件的loading状态
			if (this.$refs.search) {
				this.$refs.search.setLoading(true);
			}
			this.$refs.search.drawer=false;
			this.fomateQueryParams(queryParams,this);
			this.$API.asset.assetSummaryStatistics.selectAssetPositionSummary.post(queryParams).then((rsp =>{
				if(rsp.code === 2000){
					this.tableDatas = rsp.data;
				}
				this.loading = false;
				//释放搜索组件的loading状态
				if (this.$refs.search) {
					this.$refs.search.setLoading(false);
				}
			}));
		},
		loadChild(row,index,resolve){
			let queryParams = {};
			this.loading = true;
			if(row.pathCode){
				queryParams.pathCode = row.pathCode+','+row.levelCode;
			}
			this.fomateQueryParams(queryParams,this);
			this.$API.asset.assetSummaryStatistics.selectAssetPositionSummary.post(queryParams).then((rsp =>{
				if(rsp.code === 2000){
					if(rsp.data){
						row.children = rsp.data;
						resolve(rsp.data)
					}
				}
				this.loading = false;
			}));
		},
		//查看
		async show1(_this, row) {
			_this.loading = true;
			let positionQuery = {};
			let pathCode = row.pathCode+','+row.levelCode;
			positionQuery.pathCode = pathCode;
			_this.$API.asset.assetPosition.findAllChilds.post(positionQuery).then((rsp) =>{
				if(rsp.code === 2000){
					let queryParamst = {};
					let positionIds = []
					if(rsp.data){
						rsp.data.forEach(item =>{
							positionIds.push(item.id);
						})
					}
					positionIds.push(row.id);
					queryParamst.storePlaceIds = positionIds;
					_this.fomateQueryParams(queryParamst,_this);
					queryParamst.assetStatisticsRange = '2';
					_this.searchAsset(row.name,queryParamst);
				}
				_this.loading = false;
			});

		},
		//导出
		async export(_this,index) {
			_this.$refs.button.loading(index, true);
			let queryPrams = {};
			_this.fomateQueryParams(queryPrams,_this);
			queryPrams.exportType = "assetPosition";
			let res = await _this.$API.asset.assetSummaryStatistics.export.post(queryPrams);
			if (res.code === 2000) {
				await _this.$alert(_this.$t('common.export_request_success'), "提示", {type: 'success'}).catch(()=>{});
			}
			_this.$refs.button.loading(index, false);
		},
		formatters(row, column, cellValue, index) {
			for (const item of this.columns) {
				if (item.code === column.property){
					if (item.click) {
						if (item.fixedValue) {
							cellValue = item.fixedValue;
						} else {
							if (item.formatter) {
								if (item.formatter instanceof Function) {
									cellValue = item.formatter(row, cellValue, this);
								} else {
									cellValue = tool.format.convert(cellValue, item.formatter, item.key);
								}
							}
						}
						let label = cellValue+'';
						let clicks = item.click.split(',');
						let labels = label.split(',');
						let permissions = [];
						if (item.permissions) {
							permissions = item.permissions.split(',');
							// permissions.splice(permissions.indexOf(''), 1);
						}
						let children = [];
						clicks.forEach((click, index) => {
							let elBtn = h(ElButton, {
								link: true,
								type: 'primary',
								style: {margin: 'auto'},
								size: 'small',
								["onClick"]: () => {
									this.$options.methods[click](this, row);
									// this.$emit('columnClick', click, row);
								}
							}, () => labels[index])
							if (permissions.length > 0) {
								if (permissions.filter(item => item === click).length > 0) {
									children.push(elBtn);
								}
							} else {
								children.push(elBtn);
							}
						});
						// cellValue = h(ElButton,{link:true,type:'primary',size:'small',["onClick"]:()=>{ this.$emit('columnClick',item.click,row);}},()=>label);
						cellValue = h(ElContainer, {key: tool.uuid("elk"), style: {display: 'flex'}}, () => children);
					}else{
						if (item.formatter) {
							if (item.formatter instanceof Function) {
								cellValue = item.formatter(row, cellValue, this, index);
							} else {
								cellValue = tool.format.convert(cellValue, item.formatter, item.key);
							}
						}
					}
				}

			}
			return cellValue;
		},
		searchAsset(item,queryParams) {
			let title = "位置汇总统计"+item+"资产明细";
			//跳转到搜索台账页面
			let fromRouteId = this.$TOOL.crypto.MD5(this.$route.path);//当前页面的路由地址
			let key = this.$TOOL.crypto.MD5(item);//可以做为key的关键字段或内容
			/**
			 *  1 = 根据管理部门，根据登录账户管理范围，资产的管理部门在账户管理范围内的显示<br>
			 *  2 = 根据使用部门，根据登录账户管理范围，资产的使用部门在账户管理范围内的显示<br>
			 *  3 = 根据管理部门或使用部门，根据登录账户管理范围，资产的使用部门或管理部门在账户管理范围内的显示<br>
			 *  其它 = 根据管理部门，按台账，根据使用部门或管理部门或借用部门在管理范围内的
			 */
				//设置搜索参数
			let routeParams = {
					id: key,
					title: title,
					showXuli: true,
					fixedParams:{
						deptIds:queryParams.deptIds,
						assetCategoryIds:queryParams.assetCategoryIds,
						assetStatisticsRange: queryParams.assetStatisticsRange,
					},//固定搜索参数，打开页面后，用户通过搜索界面的清空按钮无法清除
					searchParams: queryParams
				};
			this.$store.dispatch("addRouteParams", routeParams);
			this.$router.push({
				name: "toAssetList",
				params: {fromRouteId: fromRouteId, key: key}
			});
		},
		fomateQueryParams(queryParams,_this){
			Object.assign(queryParams, _this.$refs.search.searchParams());
			if(!queryParams.deptIds||queryParams.deptIds.length===0){
				queryParams.deptIds = _this.readDeptIds;
			}
			if(!queryParams.assetCategoryIds||queryParams.assetCategoryIds.length===0){
				queryParams.assetCategoryIds = _this.manageAssetCategoryIds;
			}
			queryParams.excludeStatus = _this.excludeStatus;
		}
	}
}

</script>
<style scoped>

</style>
